from flask import g, jsonify, request, url_for, current_app, make_response
from . import api, errors
from .. import db
from ..utils.checkUpload import *
from .lovePost import getVideo
from ..models import *
from sqlalchemy import or_
import traceback

# √
# 搜索相关的表白墙
@api.route('/search', methods=['GET'])
def search():
    keyWords = request.args.get("keyWords")
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    love_post = lovePost.query.filter(
        or_(lovePost.tag.like("%"+ keyWords +"%"), lovePost.describe.like("%"+ keyWords +"%"))
    ).order_by(lovePost.publish_time.desc()).paginate(int(page), int(pageSize), False).items


    u_collections = userCollection.query.filter_by(user_id=g.current_user.user_id).all()
    u_love_post_like = userLovePostLike.query.filter_by(user_id=g.current_user.user_id).all()

    u_collections = [l.love_post_id for l in u_collections]
    u_love_post_like = [l.love_post_id for l in u_love_post_like]
    # print(u_love_post_like)

    love_posts = [l.to_json() for l in love_post]
    for love_post in love_posts:
        user = User.query.get(love_post['user_id'])
        love_post['nickName'] = user.nickName
        love_post['avatarUrl'] = user.avatarUrl

        love_post['is_collected'] = True if love_post['love_post_id'] in u_collections else False
        love_post['is_user_like'] = True if love_post['love_post_id'] in u_love_post_like else False

        if love_post['media_type'] == 'img':
            imgs = image.query.filter_by(love_post_id=love_post['love_post_id']).order_by(image.sequence_num).all()
            imgUrls = [i.img_url for i in imgs]
            love_post['imgUrls'] = imgUrls
            love_post['countOfImg'] = len(imgUrls)

        if love_post['media_type'] == 'video':
            v = video.query.filter_by(love_post_id=love_post['love_post_id']).first()
            love_post['videoUrl'] = getVideo(v.aliyun_video_id)

    response = jsonify(message='Get love post data successfully!', lovePost=love_posts)
    response.status_code = 200
    return response